package com.king.shiro;

import cn.hutool.json.JSONUtil;
import com.king.common.lang.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义Shiro过滤器，判断请求是否ajax请求
 */
public class AuthFilter extends UserFilter {
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String header = req.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header)) {//ajax请求 弹窗显示未登录
            boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
            if (!authenticated) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtil.toJsonStr(Result.fail("请先登录！")));
            }
        } else {
            super.redirectToLogin(request, response);// web 重定向到登录页面
        }
    }
}
